<template>
	<view class="content">
		<!-- 此页面是开机画面 -->
		<!-- 开机动画 -->
		<image src="../../static/gif/1.gif"></image>
		<!-- 个人信息保护指引 -->
		<uni-popup ref="guidePopup" :mask-click="false" :safe-area="false" type="dialog">
			<view class="guidePop">
				<text class="guidePop-text">免烦脑用户个人信息保护指引</text>
				<scroll-view scroll-y="true" class="scrollView"><rich-text :nodes="guideTxt"></rich-text></scroll-view>
				<view class="agreeNext flex-c" @click="agreeNext()"><text>同意并继续</text></view>
				<!-- #ifdef MP-WEIXIN -->
				<navigator class="refuseExit" target="miniProgram" open-type="exit">放弃并退出</navigator>
				<!-- #endif -->
				<!-- #ifndef MP-WEIXIN -->
				<text class="refuseExit" @click="refuseExit()">放弃并退出</text>
				<!-- #endif -->
			</view>
		</uni-popup>
	</view>
</template>

<script>
const app = getApp();
import * as api from '@/api/login';
import { isNull } from '@/utils/utils.js';
import store from '@/store';
export default {
	data() {
		return {
			title: 'Hello',
			innerAudioContext: null,
			timer: null,
			timeout: 3600,
			guideTxt: ''
		};
	},
	onLoad() {
		this.guideTxt =
				'<div style="line-height: 25px;font-size:26rpx;color: #333;text-indent:2em"><p>&nbsp;尊敬的用户，非常感谢您使用免烦脑脑血管预警头环和免烦脑监测预警服务，我们深知保护个人隐私信息的重要性，所以请您在使用前,仔细阅读并充分理解《用户协议》和《隐私政策》的内容。</p ><br/><p>如您同意《用户协议》和《隐私政策》,请点击“同意并继续”，开始使用我们的产品和服务。我们将严格按照协议及政策内容使用和保护您的个人信息，为您提供更优质的服务。</p ><br/><br/>免责声明:<br/><p>请您谨记免烦脑仅提供日常监测及风险预警服务， 监测结果与预警数据仅作为健康参考，不能作为服药依据，并不能代替医疗专业人士的临床诊断，更不具有治疗功效。免烦脑旨在对用户进行早期脑血管疾病的趋势判断及风险预警，提高用户对自身健康的认知。如果您有任何健康或医疗方面的问题，请咨询专业医疗人员。以上内容的最终解释权归江苏易爱健康科技有限公司所有，感谢您的配合与支持，祝您生活愉快。</p ></div>';
		this.loadWork()
	},
	
	onReady() {
		// 定义一个音频
		this.innerAudioContext = uni.createInnerAudioContext();
		this.innerAudioContext.autoplay = false;
		this.innerAudioContext.loop = false;
		this.innerAudioContext.src = '../../static/audio/bgm.mp3';
		this.innerAudioContext.play();
	},
	methods: {
		// 同意保护指引 后开始进入登录选择部分
		agreeNext() {
			this.$refs.guidePopup.close();
			this.toLogin()
		},
		// 拒绝 退出
		refuseExit() {
			if (uni.getSystemInfoSync().platform == 'ios') {
				plus.ios
					.import('UIApplication')
					.sharedApplication()
					.performSelector('exit');
			} else if (uni.getSystemInfoSync().platform == 'android') {
				plus.runtime.quit();
			}
		},
		loadWork(){
			// 在此处判断用户是否需要重新登录
			let that = this;
			let userInfo = store.state.userInfo;
			if (isNull(userInfo)) {
				let timeout = that.timeout;
				that.timer = setTimeout(function() {
					that.startGuide();
					clearTimeout(that.timer);
				}, timeout);
				return;
			}
			let currentUser = userInfo.currentUser;
			let appId = currentUser.appId;
			let appSecret = currentUser.appSecret;
			let userId = currentUser.userId;
			if (isNull(appId) && isNull(appSecret) && isNull(userId))
			{
				console.log('都为空，去登录。。。');
				// 跳转到登录页
				let timeout = that.timeout;
				that.timer = setTimeout(function() {
					that.startGuide();
					clearTimeout(that.timer);
				}, timeout);
			} else {
				console.log('更新 appSecret');
				let UUID = store.state.deviceUUID;
				// 将这些信息
				let data = {
					userId: userId,
					action: 'updateAppSecret',
					params: {
						appId: appId,
						appSecret: appSecret,
						uuid:UUID
					}
				};
				api.updateAppSecret(data).then(function(res) {
						console.log('updateAppSecret success', res);
						if (res.data.code == 2000) {
							try {
								that.$store.commit('token', res.data.data.token);
								if (isNull(that.$store.state.userInfo)) {
									that.timer = setTimeout(function() {
										that.startGuide();
										clearTimeout(that.timer);
									}, that.timeout);
									return;
								}
								// 每次登录app  appsecret只更新到当前用户信息中去???
								that.$store.commit('UpdateAppSecret', res.data.data.appSecret);
								//开始轮询发送tokenId 请求
								app.getTokenIdPolling();
								that.getUserInfo();
							} catch (e) {
								// error
								console.log('fail', e);
							}
						} else if (res.data.code == 2001) {
							that.timer = setTimeout(function() {
								that.startGuide();
								clearTimeout(that.timer);
							}, that.timeout);
						}
				}).catch(function(error) {
					console.log('updateAppSecret fail', error);
				});
			}
		},
		// 打开引导 仅未登录情况下
		startGuide(){
			this.$refs.guidePopup.open('center');
		},
		// 如果设备支持一键登录 就进入选择页，否则直接进入手机号登录页
		async toLogin(){
			let providState = await this.getProvidState()
			console.log('providState>>' + providState);
			if(providState) {
				this.toUniVerify()
			}else {
				this.toPhonePage()
			}
		},
		// 进入一键登录页
		toUniVerify(){
			let that = this
			uni.login({
				provider: 'univerify',
				univerifyStyle: that.$config.loginStyle,
				success(res){ // 登录成功
					console.log(res.authResult);  // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
					//调用自有服务器 获取app
					that.uniLogin(res.authResult.openid,res.authResult.access_token)
				},
				fail(err){ 
					// TODO: 除了登录成功，目前所有情况全都跳转到手机号登录页
					console.log('univerify fail',err);
					that.toPhonePage()
				}
			})
		},
		// 通过uni的方式登录
		uniLogin(uniAppOpenid,uniAppAccessToken){
			let that = this;
			let data = {
				action: 'uniAppLogin',
				params: {
					uniAppOpenid,
					uniAppAccessToken,
					role: 'EiUser',
					uuid: that.$store.state.deviceUUID
				}
			};
			api.uniLogin(data).then(function(res) {
					console.log('uniLogin success', res);
					if (res.data.code == 2000) {
						let appId = res.data.data.appIdInfo.appId;
						let appSecret = res.data.data.appIdInfo.appSecret;
						let userId = res.data.data.appIdInfo.userId;
						let phone = res.data.data.mobile
						store.commit('token', res.data.data.appIdInfo.token);
						let userInfo = uni.getStorageSync('userInfo');
						if (isNull(userInfo)) {
							// first login
							userInfo = {
								currentUser: {
									userId: userId,
									appId: appId,
									appSecret: appSecret,
									phone: phone
								},
								loginUserList: [
									{
										userId: userId,
										appId: appId,
										appSecret: appSecret,
										phone: phone
									}
								]
							};
						} else {
							// agin 将当前登录的用户信息更新到currentUser中去
							userInfo.currentUser = {
								userId: userId,
								appId: appId,
								appSecret: appSecret,
								phone: phone
							};
							let isNewUser = true;
							// 更新用户列表 (已经存在的用户就更新其个人信息 ,新用户则直接添加)
							userInfo.loginUserList.forEach(item => {
								if (item.userId == userId) {
									item.appId = appId;
									item.appSecret = appSecret;
									item.phone = phone
									isNewUser = false;
								}
							});
							if (isNewUser) {
								userInfo.loginUserList.push(userInfo.currentUser);
							}
						}
						try {
							uni.setStorageSync('userInfo', userInfo);
							store.commit('userInfo', userInfo);
							/* 轮询 tokenId */
							app.getTokenIdPolling();
							that.getUserInfo();
						} catch (e) {
							//TODO handle the exception
							console.log('缓存失败', e);
						}
					}
				}).catch(function(error) {
					console.log('uniLogin fail', error);
					uni.closeAuthView()
					that.toPhonePage()
				});
		},
		toPhonePage(){
			uni.redirectTo({
				url:'/pages/login/login'
			})
		},
		getProvidState(){
			return new Promise((resolve, reject) => {
				let that = this;
				uni.getProvider({
				  service: 'oauth',
				  success: function (res) {
					  console.log('获取一键登录环境',res);
					if(res.provider.includes('univerify')){
						resolve(true)
					}else {
						reject(false)
					}
				  },fail(err) {
				  	return false
				  }
				})
			});
		},
		getUserInfo() {
			let that = this;
			let userId = this.$store.state.userInfo.currentUser.userId;
			let data = {
				userId: userId,
				action: 'getUserInfo'
			};
			api.getUserInfo(data).then(function(res) {
					console.log('getUserInfo::', res);
					if (res.data.message == 'userInfo is null') {
						//用户未填写个人信息 跳
						that.timer = setTimeout(function() {
							uni.closeAuthView()
							uni.redirectTo({
								url: '../login/fillHealhyRecords/noInfo'
							});
							clearTimeout(that.timer);
						}, that.timeout);
					} else {
						that.$store.commit('userBaseInfo',res.data.data);
						that.timer = setTimeout(function() {
							uni.closeAuthView()
							uni.switchTab({
								url: '../detection/detection'
							});
							clearTimeout(that.timer);
						}, that.timeout);
					}
				}).catch(function(error) {
					console.log('get userInfo fail', error);
				});
		}
	}
};
</script>

<style>
page {
	background-color: #f5f5f5;
}
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 100vw;
	height: 100vh;
}

.logo {
	height: 200rpx;
	width: 200rpx;
	margin-top: 200rpx;
	margin-left: auto;
	margin-right: auto;
	margin-bottom: 50rpx;
}

.text-area {
	display: flex;
	justify-content: center;
}

.title {
	font-size: 36rpx;
	color: #8f8f94;
}
image {
	width: 100vw;
	height: 100vh;
}
.flex-c {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.guidePop {
	width: 603rpx;
	height: auto;
	background-color: white;
	border-radius: 15px;
	display: flex;
	flex-direction: column;
	align-items: center;
	/* justify-content: space-between; */
}
.guidePop-text {
	margin-top: 66rpx;
	font-size: 36rpx;
	font-family: Source Han Sans SC;
	font-weight: bold;
	color: #333333;
}
.scrollView {
	margin: 50rpx auto;
	width: 500rpx;
	height: 450rpx;
}
.agreeNext {
	width: 500rpx;
	height: 90rpx;
	border-radius: 12rpx;
	background-color: #0659c7;
}
.agreeNext text {
	font-size: 35rpx;
	font-family: Source Han Sans SC;
	font-weight: bold;
	color: white;
}
.refuseExit {
	margin-top: 30rpx;
	margin-bottom: 44rpx;
	font-size: 26rpx;
	font-family: Source Han Sans SC;
	font-weight: normal;
	color: #0659c7;
}
</style>
